package com.keepsport.keepsportapi.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keepsport.keepsportapi.dao.ActivityDao;
import com.keepsport.keepsportapi.dao.UserActivityDao;
import com.keepsport.keepsportapi.dto.UserActivityDto;
import com.keepsport.keepsportapi.entity.Activity;
import com.keepsport.keepsportapi.entity.UserActivity;
import com.keepsport.keepsportapi.service.intf.UserActivityService;
import com.keepsport.keepsportapi.vo.R;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class UserActivityServiceImpl implements UserActivityService {
    @Resource
    private UserActivityDao dao;
    @Resource
    private ActivityDao activityDao;
    @Override
    public R save(int aid, int token) {
        if(aid>0){
            Activity activity = activityDao.selectById(aid);
            if(activity==null){
                return R.fail("非常抱歉，活动已经结束");
            }else {
                if(activity.getEdate().getTime()>System.currentTimeMillis()){
                    if(activity.getMaxperson()>0){
                        if(activity.getMaxperson()<=dao.selectPersons(aid)){
                            return R.fail("非常抱歉，报名人数已经满了");
                        }
                    } 
                    QueryWrapper<UserActivity> wrapper = new QueryWrapper<>();
                    wrapper.eq("uid",token);
                    wrapper.eq("aid",aid);
                    Lock lock=new ReentrantLock();
                    lock.lock();//加锁
                    try{
                        if(dao.selectOne(wrapper)==null) {
                            //8.活动 可以报名
                            if (dao.insert(new UserActivity(aid, token)) > 0) {
                                //发送站内信  报名成功
                                return R.ok();
                            }
                        }else {
                            return R.fail("亲，您已经报过名了，请勿重复报名");
                        }
                    }finally {
                        lock.unlock();//释放锁
                    }
                }
            }
        }
        return R.fail();
    }

    @Override
    public R queryByUid(int token) {
        //1.查询数据
        List<UserActivityDto> list=dao.selectByUid(token);
        //2.为数据进行处理 区分活动的状态
        list.forEach(ua->{
            if(ua.getSdate().getTime()<System.currentTimeMillis()){
                ua.setFlag(2);
            }else if(ua.getEdate().getTime()>System.currentTimeMillis()){
                ua.setFlag(1);
            }
            else {
                ua.setFlag(3);
            }
        });

        return R.ok(list);
    }

}
